//
//  FYComposePictureView.swift
//  Weibo
//
//  Created by 冯毅 on 16/8/16.
//  Copyright © 2016年 冯毅. All rights reserved.
//

import UIKit

//  重用标记
private let FYComposePictureViewCellIdentifier = "FYComposePictureViewCellIdentifier"

//  发微博配图
class FYComposePictureView: UICollectionView {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */

    //  图片数据源
    lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        
        super.init(frame: frame, collectionViewLayout:flowLayout)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = RandomColor()
        //  注册cell
        registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: FYComposePictureViewCellIdentifier)
        //  设置数据源代理
        dataSource = self
    }
    
    
    //  添加图片方法
    func addImage(image: UIImage) {
        images.append(image)
        //  重写加载数据
        self.reloadData()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //  设置每项的间距
        let itemMargin: CGFloat = 5
        //  计算每项的大小
        let itemWidth = (width - 2 * itemMargin) / 3
        //  获取布局方式
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //  设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  设置水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //  设置垂直间距
        flowLayout.minimumLineSpacing = itemMargin
    }
}


extension FYComposePictureView:UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(FYComposePictureViewCellIdentifier, forIndexPath: indexPath)
        
        cell.backgroundColor = RandomColor()
        return cell
    }
}
